<template>
  <div class="app-container">
    <el-form ref="editCouponData" :model="editCouponData" label-width="115px">
      <el-row :gutter="24">
        <el-col :span="16" :offset="4">
          <h3 class="ticTitle">基本信息:</h3>
        </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="满减券名称:" prop="name">
            <el-input v-model="editCouponData.name" placeholder="满减劵名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="满减劵副标题:" prop="subtitle">
            <el-input v-model="editCouponData.subtitle" placeholder="优惠券副标题" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--      <el-row :span="24">-->
      <!--        <el-col :span="16" :offset="4">-->
      <!--            <el-form-item label="优惠券类型" prop="category">-->
      <!--              <el-select-->
      <!--                v-model="editCouponData.category"-->
      <!--                filterable-->
      <!--                placeholder="请选择验证方式"-->
      <!--                @change="currentSel"-->
      <!--              >-->
      <!--                <el-option-->
      <!--                  v-for="typeOption in categoryOption"-->
      <!--                  :key="typeOption.name"-->
      <!--                  :label="typeOption.name"-->
      <!--                  :value="typeOption.name"-->
      <!--                >-->
      <!--                  {{ typeOption.name }}-->
      <!--                </el-option>-->
      <!--              </el-select>-->
      <!--            </el-form-item>-->
      <!--          </el-col>-->
      <!--      </el-row>-->
      <!--          <el-col :span="12">-->
      <!--            <el-form-item v-if="totalandless" label="满" prop="discount.base">-->
      <!--              <el-col :span="8">-->
      <!--                <el-input v-model="editCouponData.templateRule.discount.base"-->
      <!--                          type='number' />-->
      <!--              </el-col>-->
      <!--              <el-col class="line" :span="1">减</el-col>-->
      <!--              <el-col :span="8">-->
      <!--                <el-input v-model="editCouponData.templateRule.discount.quota"-->
      <!--                          type='number'/>-->
      <!--              </el-col>-->
      <!--            </el-form-item>-->
      <!--            <el-form-item v-if="discount" label="折数" prop="discount.quota">-->
      <!--              <el-input v-model="editCouponData.templateRule.discount.quota"-->
      <!--                        type='number'/>-->
      <!--            </el-form-item>-->
      <!--          </el-col>-->
      <!--        </el-row>-->
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="发放数量(张)" prop="couponCount">
            <el-input v-model="editCouponData.couponCount"
                      type='number' />
          </el-form-item>
        </el-col>
      </el-row>
      <!--        <el-col :span="10">-->
      <!--          <el-form-item label="背景" prop="imgStr">-->
      <!--            <el-upload-->
      <!--              ref="upload"-->
      <!--              action="''"-->
      <!--              list-type="picture-card"-->
      <!--              :file-list="showImgs"-->
      <!--              :auto-upload="false"-->
      <!--              :http-request="uploadFile"-->
      <!--            >-->
      <!--              <i class="el-icon-plus" />-->
      <!--            </el-upload>-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->
      <!--        <el-col :span="20">-->
      <!--          <el-form-item label="描述" prop="usage">-->
      <!--            <el-input v-model="editCouponData.couponDesc" type="textarea" placeholder="规则表述" />-->
      <!--          </el-form-item>-->
      <!--        </el-col>-->

      <!--      </el-col>-->
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="使用门槛:" prop="usage">
            <el-radio-group v-model="editCouponData.category" @change="usageShow" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:230px">
                <el-radio label="0">
                  无门槛
                </el-radio>
                <el-radio label="1">
                  消费金额
                </el-radio>
              </el-form-item>
              <el-form-item v-if="tickKindShow" style="display:inline-block;margin-right:10px;vertical-align:top;width:calc(100% - 240px);float:right;margin-right: 0px">
                <el-input  v-model="editCouponData.templateRule.discount.base" style="width:100%" ></el-input>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="优惠券内容:">
            <span style="display:inline-block;margin-right:0px;vertical-align:top;width:110px">减免金额(元)</span>
            <el-input v-model="editCouponData.templateRule.discount.quota" style="display:inline-block;vertical-align:top;width:calc(100% - 110px);float:right;margin-right: 0px"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="适用商品:" prop="usage">
            <el-radio-group v-model="editCouponData.templateRule.usage.usageType" @change="showSelectProducts" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:230px">
                <el-radio label="0">
                  全部商品
                </el-radio>
                <el-radio label="1">
                  指定商品可用
                  <button v-if="selectProducts">选择商品</button>
                </el-radio>
                <el-radio label="2">
                  指定商品不可用
                  <button v-if="unSelectProducts">选择商品</button>
                </el-radio>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :span="24"><el-col :sapn="16" :offset="4">
        <h3 class="ticTitle">基本信息:</h3>
      </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="领取人限制:" prop="usage">
            <el-radio-group v-model="editCouponData.templateRule.receive.receiveType" @change="useLimitation" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:260px">
                <el-radio label="0">
                  所有用户可领
                </el-radio>
                <el-radio label="1">
                  指定用户领取
                </el-radio>
              </el-form-item>
              <el-form-item style="display:inline-block;margin-right:10px;vertical-align:top;width:calc(100% - 270px);float:right;margin-right: 0px">
                <el-select
                  v-model="editCouponData.templateRule.receive.userType"
                  filterable
                  placeholder="请选择用户"
                  style="width:100%"
                  v-if="assignUser"
                >
                  <el-option
                    v-for="userApply in userApplyOptions"
                    :key="userApply.code"
                    :label="userApply.name"
                    :value="userApply.code"
                  >
                    {{ item.name }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>



      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="每人限领:" prop="usage">
            <el-radio-group v-model="editCouponData.templateRule.limitation.limitationType" @change="defineDaraw" style="width:100%">
              <el-form-item style="display:inline-block;margin-right:0px; vertical-align:top;width:200px">
                <el-radio label="0">
                  不限次数
                </el-radio>
                <el-radio label="1">
                  限定次数
                </el-radio>
              </el-form-item>
              <el-form-item style="display:inline-block;margin-right:10px;vertical-align:top;width:calc(100% - 210px);float:right;margin-right: 0px">
                <el-input v-if="showDefineCount" v-model="editCouponData.templateRule.limitation.limitation"  style="width:100%"></el-input>
              </el-form-item>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>


      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="有效日期:" prop="limitTime">
            <el-radio-group v-model="editCouponData.templateRule.expiration.period" @change="limitTimeShow" style="width:100%">

              <el-form-item label="" prop="effectiveDate">
                <el-col :span="24">
                  <el-radio label="0" style="width:100%">
                    有效日期
                    <el-time-picker
                      v-if="effectiveShow"
                      v-model="effectiveDate"
                      value-format="timestamp"
                      is-range
                      range-separator="至"
                      start-placeholder="开始时间"
                      end-placeholder="结束时间"
                      placeholder="选择时间范围"
                      style="width:93%"
                    />
                  </el-radio>
                </el-col>
              </el-form-item>
              <el-col :span="24">
                <el-radio label="1" style="width:100%">领取优惠后，当天生效，有效期天数
                  <el-input v-if="getCouponDateShow" v-model="editCouponData.templateRule.expiration.gap"
                            type='number'style="width:77%" />
                </el-radio>
              </el-col>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :span="24">
        <el-col :span="16" :offset="4">
          <el-form-item label="跳转链接" prop="url">
            <el-input v-model="editCouponData.url" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-footer height="80px">
        <el-row style="display: flex;justify-content: center;align-items: center;">
          <el-button @click="submit" type="primary">
            保存
          </el-button>
          <el-button @click="editOut">
            取消
          </el-button>
        </el-row>
      </el-footer>
    </el-form>
  </div>
</template>

<script>
import { replaceSpacesObj } from '../../../utils/webUtils.js'

export default {
  name: 'EditTict',
  components: {},
  props: {
    tictUuid: {
      type: String
    }
  },
  data() {
    return {
      uuid: this.tictUuid,
      editCouponData: {
        id:this.uuid,
        name: '',
        subtitle: '',
        category: '',
        categoryName:'',
        businessLine: '',
        businessLineName: '',
        backgroudImg: '',
        distributeTarget: '',
        url: '',
        available: '',
        couponDesc: '',
        couponCount: '',
        templateRule:{
          expiration:{
            period:'',
            gap:'',
            startTime:'',
            endTime:''
          },
          receive:{
            receiveType:'',
            userType:''
          },
          discount:{
            quota:'',
            base:''
          },
          limitation: {limitation:'',limitationType:''},
          usage:{
            usageType:'',
            userType:'',
            goodsType:'',
            goodsIds:''
          },
        },
      },
      categoryOption:[],
      effectiveDate:'',
      shiyDta:[],
      showImgs: [],
      list: [],
      validOptions: {},
      yardOptions: [],
      mercList: [],
      merchants: { name: '', uuid: '' },
      tickValue: [],
      validationOptions: [],
      applyUserOption: [],
      applyShowOption: [],
      couponTypeOption: [],
      selVal: '',
      rules: {},
      info: '',
      infoShow: false,
      imgList: [],
      imgformData: {},
      editBoxShow: false,
      displayDate: false,
      totalandless: false,
      discount: false,
      effectiveShow: false,
      getCouponDateShow: false,
      tickKindShow: false,
      assignUser:false,
      showDefineCount:false,
      selectProducts:false,
      unSelectProducts:false
    }
  },
  watch: {
    tictUuid(val) {
      this.uuid = val
      this.queryCouponTic();
    }
  },
  mounted() {
    this.uuid=this.$route.params.uuid
    this.queryApplyUser()
    this.queryApplyShow()
    this.querycouponType()
    this.queryCouponTic()
    this.querycategory()
  },
  methods: {

    useLimitation(){
      if (this.editCouponData.templateRule.receive.receiveType == '0') {
        this.assignUser = false
        this.editCouponData.templateRule.receive.userType=''
      } else if (this.editCouponData.templateRule.receive.receiveType == '1') {
        this.assignUser=true
      }
    },
    showSelectProducts(){
      if (this.editCouponData.templateRule.usage.usageType == '1') {
        this.selectProducts = true
        this.unSelectProducts=false
        this.editCouponData.templateRule.usage.goodsIds=''
      } else if (this.editCouponData.templateRule.usage.usageType == '2') {
        this.unSelectProducts=true
        this.selectProducts=false
        this.editCouponData.templateRule.usage.goodsIds=''
      }else{
        this.selectProducts=false
        this.unSelectProducts=false
        this.editCouponData.templateRule.usage.goodsIds=''
        this.editCouponData.templateRule.usage.unGoodsIds=''
      }
    },
    defineDaraw(){
      if (this.editCouponData.templateRule.limitation.limitationType == '0') {
        this.showDefineCount = false
        this.editCouponData.templateRule.limitation.limitation=''
      } else if (this.editCouponData.templateRule.limitation.limitationType == '1') {
        this.showDefineCount=true
      }
    },
    usageShow() {
      if (this.editCouponData.category == '0') {
        this.tickKindShow = false
        this.editCouponData.templateRule.discount.base=''
      } else if (this.editCouponData.category == '1') {
        this.tickKindShow = true
        this.editCouponData.templateRule.discount.base=''
      } else {
        this.tickKindShow = false
        this.editCouponData.templateRule.usage.discount.base=''
      }
    },
    querycategory() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/coupon_Type',
          params: {}
        })
        .then(response => {
          this.categoryOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // handleRemove(file, fileList) {
    //   console.log(file)
    //   console.log(fileList)
    //   for (var i in this.fileList) {
    //     if (fileList[i].uid == file.uid) {
    //       var count = --i;
    //       fileList.splice(count, 1);
    //     }
    //   }
    //   this.showImgs=fileList
    //   this.list=[]
    //   if(this.showImgs.length>0) {
    //     this.showImgs.forEach(res => {
    //       this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('coupon'))})
    //     })
    //     this.editCouponData.backgroudImg = JSON.stringify(this.list)
    //     console.log("删除"+ this.editCouponData.backgroudImg )
    //   }else{
    //     this.editCouponData.backgroudImg=''
    //   }
    //
    // },
    // uploadFile(item){
    //   if(item.file!=null&&item.file!=''){
    //     console.log("之前imgStr"+this.editCouponData.backgroudImg)
    //     let formData = new FormData();
    //
    //     formData.append('upFile', item.file);
    //     this.axios.post(
    //       "./coupon/coupon/template/upload/img/"+this.uuid,formData
    //     ).then(res=>{
    //       var data=res.data.data;
    //       this.list.push({'filename':data.filename,'url':data.url})
    //
    //       this.editCouponData.backgroudImg = JSON.stringify(this.list)
    //       console.log("之后imgStr"+this.editCouponData.backgroudImg)
    //       if(this.editCouponData.backgroudImg.length>0){
    //         this.uploadImg();
    //       }
    //
    //     }).catch(error => {
    //       this.dataFail("上传活动背景失败")
    //     });
    //   }else{
    //     this.editCouponData.backgroudImg = ''
    //   }
    // },
    limitTimeShow() {
      if (this.editCouponData.templateRule.expiration.period == '0') {
        this.effectiveShow = true
        this.getCouponDateShow = false
        this.editCouponData.templateRule.expiration.gap=''
      } else if (this.editCouponData.templateRule.expiration.period == '1') {
        this.effectiveShow = false
        this.getCouponDateShow = true
        this.effectiveDate = ''
      } else {
        this.effectiveShow = false
        this.getCouponDateShow = false
      }
    },




    queryCouponTic() {
      console.log("之后uuid"+this.uuid)
      this.axios.request({
        method: 'get',
        url: './coupon/coupon/template/' + this.uuid,
        headers: {},
        params: {}
      }).then(response => {
        this.insertCoupon(response.data.data)
      }).catch(error => {
        console.log(error)
      })
    },
    insertCoupon(couponTic) {
    this.editCouponData.name=couponTic.name,
    this.editCouponData.subtitle=couponTic.subtitle,
      this.editCouponData.category=couponTic.category,
      this.editCouponData.categoryName=couponTic.categoryName,
      this.editCouponData.businessLine=couponTic.businessLine,
      this.editCouponData.businessLineName=couponTic.businessLineName,
      this.editCouponData.backgroudImg=couponTic.backgroudImg,
      this.editCouponData.distributeTarget=couponTic.distributeTarget,
      this.editCouponData.url=couponTic.url,
      this.editCouponData.couponCount=couponTic.couponCount,
      this.editCouponData.available=couponTic.available,
      this.editCouponData.couponDesc=couponTic.couponDesc,
      this.editCouponData.templateRule.usage.goodsIds=couponTic.templateRule.usage.goodsIds,
      this.editCouponData.templateRule.usage.usageType=couponTic.templateRule.usage.usageType,
      this.editCouponData.templateRule.usage.goodsType=couponTic.templateRule.usage.goodsType,
      this.editCouponData.templateRule.expiration.period=couponTic.templateRule.expiration.period,
      this.editCouponData.templateRule.expiration.gap=couponTic.templateRule.expiration.gap,
      this.editCouponData.templateRule.expiration.startTime=couponTic.templateRule.expiration.startTime,
      this.editCouponData.templateRule.expiration.endTime=couponTic.templateRule.expiration.endTime,
      this.editCouponData.templateRule.discount.quota=couponTic.templateRule.discount.quota,
      this.editCouponData.templateRule.discount.base=couponTic.templateRule.discount.base,
      this.editCouponData.templateRule.receive.receiveType=couponTic.templateRule.receive.receiveType
      this.editCouponData.templateRule.receive.userType=couponTic.templateRule.receive.userType
      this.editCouponData.templateRule.limitation.limitationType=couponTic.templateRule.limitation.limitationType
      this.editCouponData.templateRule.limitation.limitation=couponTic.templateRule.limitation.limitation
      this.editCouponData.templateRule.limitation=couponTic.templateRule.limitation
      if(this.editCouponData.templateRule.expiration.startTime!=null&&this.editCouponData.templateRule.expiration.startTime!=''
        &&this.editCouponData.templateRule.expiration.endTime!=null&&this.editCouponData.templateRule.expiration.endTime!=''){
      this.shiyDta.push(this.editCouponData.templateRule.expiration.startTime);
      this.shiyDta.push(this.editCouponData.templateRule.expiration.endTime);
      this.effectiveDate=this.shiyDta
      }
      this.usageShow()
      this.defineDaraw()
      this.showSelectProducts()
      this.useLimitation()
      this.limitTimeShow()
    },
    quertImgRelook(){
      if(this.editCouponData.backgroudImg != null && this.editCouponData.backgroudImg != ''){
        this.showImgs = [];
        JSON.parse(this.editCouponData.backgroudImg).forEach(res=>{
          this.showImgs.push({'name':res.filename,'url':"http://39.106.30.94/respu/"+res.url})
        })
      }
    },
    /* applyUser(){
             this.editCouponData.applyScopea=this.editCouponData.applyUser.toString();
             },
             applyShow(){
                 this.editCouponData.applyScopea=this.editCouponData.applyShow.toString();
             },*/
    querycouponType() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/coupon_Type',
          params: {}
        })
        .then(response => {
          this.couponTypeOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    queryApplyUser() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_USER',
          params: {}
        })
        .then(response => {
          this.applyUserOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    queryApplyShow() {
      this.axios
        .request({
          method: 'get',
          url: './kwp/kdi/para/code/TCK_TYPE',
          params: {}
        })
        .then(response => {
          this.applyShowOption = response.data.subParas
        })
        .catch(error => {
          console.log(error)
        })
    },
    // imgSubmit(){
    //   if(this.showImgs.length>0) {
    //     this.showImgs.forEach(res => {
    //       this.list=[]
    //       this.list.push({'filename': res.name, 'url': res.url.substr(res.url.lastIndexOf('coupon'))})
    //     })
    //     this.editCouponData.backgroudImg = JSON.stringify(this.list)
    //   }
    //   this.$refs.upload.submit()
    //   },
    // uploadImg(){
    //   this.editCouponData.id=this.uuid
    //   console.log("之后id"+this.uuid)
    //   console.log("之前imgStr"+this.editCouponData.backgroudImg)
    //   this.axios.request({
    //     method: "put",
    //     url: "./coupon/coupon/template/updateTemplate",
    //     headers: {
    //       "Content-Type": "application/json;charset=UTF-8"
    //     },
    //     data: replaceSpacesObj(this.editCouponData)
    //   }).then(() => {
    //   }).catch(error => {
    //     console.log(error);
    //     this.info = '上传图片后回写imgStr数据失败！';
    //     this.infoShow = true;
    //     this.dataFail("上传图片回写数据失败")
    //   });
    // },
    submit() {
      this.editCouponData.id=this.uuid
      console.log("id="+this.editCouponData.id)
      this.$refs['editCouponData'].validate((valid) => {
        if (!valid) {
          return
        }
        this.axios.request({
          method: 'put',
          url: './coupon/coupon/template/updateTemplate',
          headers: {
            'Content-Type': 'application/json;charset=UTF-8'
          },
          data: replaceSpacesObj(this.editCouponData)

        }).then(response => {
          this.dataSucess("修改数据成功");
          // this.imgSubmit();
          this.editOut();
        }).catch(error => {
          console.log(error)
          this.info = '票务新增失败'
          this.infoShow = true
        })
      })
    },
    // closDisplay(){
    //   this.$emit("close");
    // },
    dataSucess(message) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success'
      });
    },
    dataFail(message) {
      this.$notify({
        title: '失败',
        message: message,
        type: 'error'
      });
    },
    endProcessing() {
      this.info = this.info + '新增成功,两秒后关闭'
      this.infoShow = true
      setTimeout(() => {
        this.infoShow = false
        this.$emit('editState', false)
        this.cleanHrom()
        this.info = ''
      }, 2000)
    },
    cleanHrom() {
      this.editCouponData = {
        couponName: '',
        couponTitle: '',
        couponType: '',
        couponMan: '',
        couponJian: '',
        provideNumber: '',
        describe: '',
        imgStr: '',
        applyScope: '',
        applyScopeValue: '',
        applyUser: '',
        applyShow: '',
        limitCollection: '',
        redirectInter: '',
        effectiveDate: '',
        limitTime: '',
        limitTimeValue: '',
        getCouponDate: ''
      }
    },
    editOut() {
      this.$router.push("/couponList")
    }
  }
}
</script>

<style scoped lang="scss">
  @import "../../../styles/addTict";

</style>
